package com.example.Activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.entity.User;
import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends Activity implements View.OnClickListener {
    ImageView iv_login;
    EditText et_username,et_password;
    Button btn_login;
    CheckBox remember_pass;
    TextView tv_register;
    private SharedPreferences pref;
    private SharedPreferences.Editor editor;
    static final String URL = "http://120.24.37.161:8080/17376058_CZP_FinalTest/login";

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){
        public void handleMessage(Message msg){
            switch (msg.what){
                case 0:
                    Toast.makeText(LoginActivity.this, "账户或密码输入错误", Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    Gson gson = new Gson();
                    User user = gson.fromJson((String) msg.obj,User.class);
                    String username = user.getUsername();
                    Intent intent = new Intent(LoginActivity.this,CateActivity.class);
                    intent.putExtra("username",username);
                    startActivity(intent);
                    finish();
                    break;
                case 2:
                    Toast.makeText(LoginActivity.this, "当前无网络,不知道的问题", Toast.LENGTH_LONG).show();
                    break;
                    default:
                        break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_activity);
        initView();
        initEvent();
        pref = PreferenceManager.getDefaultSharedPreferences(this);
        boolean isRemember = pref.getBoolean("remember_pass", false);
        if(isRemember) {
            //将账号和密码都设置到文本框中
            String username = pref.getString("et_number", "");
            String password = pref.getString("et_password", "");
            et_username.setText(username);
            et_password.setText(password);
            remember_pass.setChecked(true);
        }
    }

    private void initView() {
        et_username = findViewById(R.id.et_username);
        et_password = findViewById(R.id.et_password);
        btn_login = findViewById(R.id.btn_login);
        remember_pass = findViewById(R.id.remember_pass);
        tv_register = findViewById(R.id.tv_register);
    }

    private void initEvent() {
        btn_login.setOnClickListener(this);
        remember_pass.setOnClickListener(this);
        tv_register.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_login:
//                if (ContextCompat.checkSelfPermission(LoginActivity.this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
//                    ActivityCompat.requestPermissions(LoginActivity.this, new String[]{Manifest.permission.INTERNET}, 4);
//                } else {
//                    LoginOkHttp();
//                }
                LoginOkHttp();
//                    Login();
                break;
            case R.id.remember_pass:
                    Remember();
                break;
            case R.id.tv_register:
                Intent in1 = new Intent("com.example.activity's.ACTION_START");
                startActivity(in1);
//                finish();
                break;

        }
    }

    private void LoginOkHttp() {
        if((et_username.getText().toString() != null&&et_username.getText().toString().length() != 0)
                &&(et_password.getText().toString() != null&&et_password.getText().toString().length() != 0)){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        OkHttpClient client = new OkHttpClient();
                        RequestBody requestBody = new FormBody.Builder()
                                .add("username",et_username.getText().toString())
                                .add("password",et_password.getText().toString())
                                .build();
                        Request request = new Request.Builder()
                                .url(URL)
                                .post(requestBody)
                                .build();
                        Response response = client.newCall(request).execute();
                        String loginData = response.body().string();
                        Log.d("123","123"+loginData);
                        if (loginData.equals("0")){
                            Message message = new Message();
                            message.what = 0;
                            handler.sendMessage(message);
                        }else {
                            Message message = new Message();
                            message.what = 1;
                            message.obj = loginData;
                            handler.sendMessage(message);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        Message message = new Message();
                        message.what = 2;
                        handler.sendMessage(message);
                    }
                }
            }).start();
        }else {
            Toast.makeText(LoginActivity.this, "不符合要求,用户或密码不能为空", Toast.LENGTH_LONG).show();
        }
//        String username = et_username.getText().toString();
//        String password = et_password.getText().toString();
//        if (username.equals("czp")&&password.equals("123")){
//            Intent intent = new Intent(LoginActivity.this,CateActivity.class);
//            startActivity(intent);
//            finish();
//        }else {
//            Toast.makeText(LoginActivity.this,"用户或密码无效",Toast.LENGTH_SHORT).show();
//        }

    }

    private void Remember() {
        String username = et_username.getText().toString();
        String password = et_password.getText().toString();
        if(!username.equals("")&&!password.equals("")) {
            editor = pref.edit();
            if(remember_pass.isChecked()) {
                editor.putBoolean("remember_pass", true);
                editor.putString("et_number", username);
                editor.putString("et_password", password);
            }
            else {
                editor.clear();
            }
            editor.apply();
            Toast.makeText(LoginActivity.this, "保存成功", Toast.LENGTH_LONG).show();
        }
        else {
            Toast.makeText(LoginActivity.this, "用户或密码为空", Toast.LENGTH_SHORT).show();
        }
    }
}
